﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Authorization;
using Nacos.AspNetCore;
using ProjectManApi.Extensions;
using BusinessEntity.xmglQuerryEntity;
using System.Data;
using learun.util;
using BusinessRule;
//using BusinessRule.XMList;
using BusinessEntity;
using Newtonsoft.Json.Linq;
using BusinessRepository;
using System.Dynamic;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Net;

namespace ProjectManApi.Controllers.xmgl
{
    public class ProTZJHController : MvcControllerBase
    {

        private readonly INacosServerManager _serverManager;
        public ProTZJHController(INacosServerManager serverManager) : base(serverManager)
        {
            _serverManager = serverManager;
        }

        #region 支付完成回调
        /// <summary>
        /// 支付完成接口的
        /// </summary>
        /// <param name="PSJson"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> ReturnPaymentStatus(dynamic PSJson)
        {
            try
            {
                string strsqid = PSJson.contractApplicationId;//申请id
                string strhtid = PSJson.contractId;//合同编号
                string strhtlx = PSJson.contractType;//合同类型
                string strhtje = PSJson.contractAmount;//合同金额

                //项目管理这边要除100 
                string strzfje = PSJson.amount;//支付金额
                decimal zfje = strzfje.ToDecimal() / 100;
                string commonId = PSJson.commonId;
                string approveStatus = PSJson.approveStatus;//审批状态

                //记录日志
                LogEntity logEntity = new LogEntity();
                logEntity.F_CategoryId = 3;
                logEntity.F_OperateTypeId = ((int)OperationType.AuditPay).ToString();
                logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.AuditPay);
                logEntity.F_OperateAccount = ContextHelper.GetItem("userName") as string;
                logEntity.F_OperateUserId = ContextHelper.GetItem("userId") as string;
                logEntity.F_Module = Request.Path;
                logEntity.F_IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                logEntity.F_ExecuteResult = -1;
                logEntity.F_ExecuteResultJson = Newtonsoft.Json.JsonConvert.SerializeObject(PSJson);
                await LogRule.Write(logEntity);


                //项目有申请id
                if (strhtlx == BaseEditPower.ModuleName.项目合同.ToString())
                {
                    if (!string.IsNullOrEmpty(strsqid))
                    {
                        string struid = GetUserId();


                        CProFKMX fkmx = new CProFKMX();
                        fkmx.id = CommonHelper.GetUniqueId().ToString();
                        fkmx.sqid = strsqid;
                        //这里要除以100
                        fkmx.zfje = zfje;
                        fkmx.createdate = DateTime.Now;
                        fkmx.createuser = struid;

                        //新增
                        //await new RepositoryFactory().BaseRepository().Insert(fkmx);
                        if (approveStatus == "checked")
                            //新增
                            await new RepositoryFactory().BaseRepository().Insert(fkmx);
                        else
                            await new RepositoryFactory().BaseRepository().DeleteAny<CProFKMX>(new { sqid = strsqid });

                        _logger.Info("用户" + struid + "在做合同支付操作");
                    }
                    else
                    {
                        throw new Exception("操作失败，申请id不存在");
                    }
                }
                else
                {
                    string struid = GetUserId();
                    CProFKMX fkmx = new CProFKMX();
                    //fkmx.id = CommonHelper.GetUniqueId().ToString();
                    fkmx.id = strhtid;
                    fkmx.sqid = strsqid;
                    fkmx.zfje = strzfje.ToDecimal() / 100;
                    fkmx.createdate = DateTime.Now;
                    fkmx.createuser = struid;

                    //新增付款记录
                    await BusinessRule.Contract.InsertHT_Order(struid, fkmx.id, fkmx.zfje, fkmx.createdate, fkmx.createuser, approveStatus, commonId);
                }

                return Json(new ResParameter { code = ResponseCode.success, message = "成功" });
            }
            catch (Exception ex)
            {
                return Json(new ResParameter { code = ResponseCode.fail, message = "操作失败" + ex.Message });
            }
        }
        #endregion

        #region 项目管理各个模块关联关系
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> GetSaveFunGL(Dictionary<string, string> Funjson)//
        {
            string strope = "add";
            List<BDicInfoFun> funs = new List<BDicInfoFun>();
            try
            {

                foreach (var item in Funjson)
                {
                    string strkey = item.Key;
                    if (strkey.ToLower() == "ope")
                    {
                        strope = item.Value;
                    }
                    else
                    {
                        string strvalue = item.Value;
                        funs.Add(new BDicInfoFun() { funid = strkey, nouse = strvalue });
                    }
                }

                //获取方法
                //strope = Funjson.ope;
                //strope = strope.ToLower();

                //investmentplan 付款计划
                //Projectbudget 项目概算
                //Purchaserequest 采购申请
                //Sitemanagement 现场管理
                //Monthlypaymentplan 月付款计划

                //var ddd = (IDictionary<string, Object>)(Funjson);



                if (strope != "add" && strope != "edit")
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }

            try
            {
                await CProTZJHRule.GetSaveFunGL(funs, strope, GetUserId());

                return Success("成功");
            }
            catch (Exception ex)
            {
                //_logger.Log(LogLevel.Info, this.Url.Action() + zc.ToJson());
                _logger.Error(ex.Message);
                return Fail("响应失败:" + ex.Message);
            }
        }

        //[HttpPost]
        //[AllowAnonymous]
        //public async Task<IActionResult> GetSaveFunGL(dynamic Funjson)//
        //{
        //    string strope = "add";
        //    List<BDicInfoFun> funs = new List<BDicInfoFun>();
        //    try
        //    {


        //        //获取方法
        //        strope = Funjson.ope;
        //        strope = strope.ToLower();

        //        //investmentplan 付款计划
        //        //Projectbudget 项目概算
        //        //Purchaserequest 采购申请
        //        //Sitemanagement 现场管理
        //        //Monthlypaymentplan 月付款计划

        //        //var ddd = (IDictionary<string, Object>)(Funjson);

        //        string investmentplan = Funjson.investmentplan;
        //        string Projectbudget = Funjson.Projectbudget;
        //        string Purchaserequest = Funjson.Purchaserequest;
        //        string Sitemanagement = Funjson.Sitemanagement;
        //        string Monthlypaymentplan = Funjson.Monthlypaymentplan;
        //        string ContractMoneyLimit = Funjson.ContractMoneyLimit;
        //        //申请金额和计划金额
        //        string PayMoneyLimit = Funjson.PayMoneyLimit;

        //        funs.Add(new BDicInfoFun() { funid = "investmentplan", nouse = investmentplan });
        //        funs.Add(new BDicInfoFun() { funid = "Projectbudget", nouse = Projectbudget });
        //        funs.Add(new BDicInfoFun() { funid = "Purchaserequest", nouse = Purchaserequest });
        //        funs.Add(new BDicInfoFun() { funid = "Sitemanagement", nouse = Sitemanagement });
        //        funs.Add(new BDicInfoFun() { funid = "Monthlypaymentplan", nouse = Monthlypaymentplan });

        //        funs.Add(new BDicInfoFun() { funid = "ContractMoneyLimit", nouse = ContractMoneyLimit });

        //        funs.Add(new BDicInfoFun() { funid = "PayMoneyLimit", nouse = PayMoneyLimit });

        //        //JObject job = (JObject)Funjson;
        //        ////获取实体类 这样复杂类型不用定义实体类
        //        //funs = job["funs"].ToObject<List<BDicInfoFun>>();


        //        if (strope != "add" && strope != "edit")
        //        {
        //            return Fail("参数ope 不合法");
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        return Fail("参数转换出错：" + ex.Message);
        //    }

        //    try
        //    {
        //        await CProTZJHRule.GetSaveFunGL(funs, strope, GetUserId());

        //        return Success("成功");
        //    }
        //    catch (Exception ex)
        //    {
        //        //_logger.Log(LogLevel.Info, this.Url.Action() + zc.ToJson());
        //        _logger.Error(ex.Message);
        //        return Fail("响应失败:" + ex.Message);
        //    }
        //}

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> GetFunGLLists()//string strdwid
        {
            try
            {
                //investmentplan 付款计划
                //Projectbudget 项目概算
                //Purchaserequest 采购申请
                //Sitemanagement 现场管理
                //Monthlypaymentplan 月付款计划

                //dynamic d = new ExpandoObject();
                var d = new ExpandoObject() as IDictionary<string, Object>;
                var dataTable = await CProTZJHRule.GetFunGLList();
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    string funid = dataTable.Rows[i]["funid"].ToString().Trim();


                    d.Add(funid, dataTable.Rows[i]["nouse"].ToString());

                    //if (funid == "investmentplan")
                    //{
                    //    d.investmentplan = dataTable.Rows[i]["nouse"].ToString();
                    //}
                    //if (funid == "Projectbudget")
                    //{
                    //    d.Projectbudget = dataTable.Rows[i]["nouse"].ToString();
                    //}
                    //if (funid == "Purchaserequest")
                    //{
                    //    d.Purchaserequest = dataTable.Rows[i]["nouse"].ToString();
                    //}
                    //if (funid == "Sitemanagement")
                    //{
                    //    d.Sitemanagement = dataTable.Rows[i]["nouse"].ToString();
                    //}
                    //if (funid == "Monthlypaymentplan")
                    //{
                    //    d.Monthlypaymentplan = dataTable.Rows[i]["nouse"].ToString();
                    //}
                    ////合同金额
                    //if (funid == "ContractMoneyLimit")
                    //{
                    //    d.ContractMoneyLimit = dataTable.Rows[i]["nouse"].ToString();
                    //}
                    ////申请金额
                    //if (funid == "PayMoneyLimit")
                    //{
                    //    d.PayMoneyLimit = dataTable.Rows[i]["nouse"].ToString();
                    //}
                }

                return Success(d);
            }
            catch (Exception ex)
            {
                return Fail("查询失败：" + ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetFunGLBylx(string lx)//string strdwid
        {
            try
            {
                //investmentplan 付款计划
                //Projectbudget 项目概算
                //Purchaserequest 采购申请
                //Sitemanagement 现场管理
                //Monthlypaymentplan 月付款计划

                dynamic d = new ExpandoObject();

                var nouse = await CProTZJHRule.GetFunGLListBylx(lx);

                string sfgl = "";
                sfgl = nouse == "1" ? "是" : "否";

                //for (int i = 0; i < dataTable.Rows.Count; i++)
                //{
                //    string nouse = dataTable.Rows[i]["nouse"].ToString().Trim();

                //}

                return Success(sfgl);
            }
            catch (Exception ex)
            {
                return Fail("查询失败：" + ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetFunGLBylxMulti(string lx)//string strdwid
        {
            try
            {
                //investmentplan 付款计划
                //Projectbudget 项目概算
                //Purchaserequest 采购申请
                //Sitemanagement 现场管理
                //Monthlypaymentplan 月付款计划

                string[] strlxs = lx.Split(',');

                //dynamic d = new ExpandoObject();
                var d = new ExpandoObject() as IDictionary<string, Object>;
                //x.Add("NewProp", string.Empty);

                for (int i = 0; i < strlxs.Length; i++)
                {
                    string funid = strlxs[i];
                    var nouse = await CProTZJHRule.GetFunGLListBylx(funid);

                    string sfgl = nouse == "1" ? "是" : "否";


                    d.Add(funid, sfgl);
                }





                return Success(d);
            }
            catch (Exception ex)
            {
                return Fail("查询失败：" + ex.Message);
            }
        }
        #endregion

        #region 校验采购了哪些模块
        [HttpGet]
        public async Task<IActionResult> GetDicModuleManager()//
        {
            try
            {
                string strbuyModule = ConfigHelper.GetAppSettings("ServerOp:buyModule");
                //判断是否购买项目管理模块
                _logger.Debug("是否购买项目管理模块");

                string stradmin = ConfigHelper.GetAppSettings("ServerOp:SerAdmin");
                List<JavaApi.DataItemDIC> list = await XMListRule.Getdics(strbuyModule, await GetICApiInfo(stradmin));
                _logger.Debug("是否购买项目管理模块：" + list.ToJson());

                return Success(list);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        #endregion

        #region 获取用户名和部门名
        [HttpGet]
        public async Task<IActionResult> GetUserInfo()//
        {
            try
            {
                dynamic d = new ExpandoObject();

                d.id = GetUserId();
                d.realname = GetUserName();
                d.deptId = GetUserDeptid();
                d.deptName = GetUserDeptName();

                return Success(d);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }

        }

        #endregion

        #region 导入 投资计划

        #region 下载模板
        [HttpGet]
        [AllowAnonymous]
        public IActionResult DownLoadTemplateTZJH()
        {
            string baseDir = ConfigHelper.GetValue<string>("baseDir");
            //string strpath = baseDir + "\\UpLoad\\Template\\tzjh.xlsx";
            string strpath = baseDir + "/UpLoad/Template/tzjh.xlsx";
            return File(FileHelper.Read(strpath), "application/ms-excel", "投资计划导入模板.xlsx");
        }
        #endregion

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> ImportTZJH([FromForm] IFormCollection formCollection)
        {
            try
            {
                //if (string.IsNullOrEmpty(strzbid))
                //{
                //    return Fail("招标编号strzbid不能为空");
                //}

                string baseDir = ConfigHelper.GetValue<string>("baseDir");

                if (formCollection.Files.Count == 0)
                {
                    return Fail("请上传文件");
                }
                FormFileCollection filelist = (FormFileCollection)formCollection.Files;
                string nfilepath = "";
                foreach (IFormFile file in filelist)
                {
                    String Tpath = "/UpLoad/项目/";
                    string name = file.FileName;
                    string FileName = CommonHelper.GetUniqueId().ToString();
                    string FilePath = baseDir + Tpath;

                    string type1 = Path.GetExtension(name);
                    DirectoryInfo di = new DirectoryInfo(FilePath);

                    if (!di.Exists)
                    {
                        di.Create();
                    }

                    using (FileStream fs = System.IO.File.Create(FilePath + FileName + type1))
                    {
                        // 复制文件
                        file.CopyTo(fs);
                        // 清空缓冲区数据
                        fs.Flush();
                    }
                    nfilepath = FilePath + FileName + type1;
                }

                DataTable ds = ExcelHelper.ExcelImport(nfilepath);
                //List<dynamic> lists = new List<dynamic>();
                //for (int i = 0; i < ds.Rows.Count; i++)
                //{
                //    dynamic jh = new ExpandoObject();
                //    jh.id = CommonHelper.GetUniqueId().ToString();

                //    //投资项目名称	出资单位	出资金额	出资比例	投资类型	项目性质	计划开始时间	计划结束时间	项目总投资	资金来源	计划年度	计划投资资金	计划安排资金
                //    jh.tzxmmc = ds.Rows[i][0].ToString();//投资项目
                //    jh.czdw = ds.Rows[i][1].ToString();
                //    jh.czje = ds.Rows[i][2].ToString().ToDecimal();
                //    jh.tzlx = ds.Rows[i][3].ToString();
                //    jh.xmxz = ds.Rows[i][4].ToString();//项目性质

                //    jh.xmkssj = ds.Rows[i][5].ToString().ToDate().Year == 1 ? DateTime.Now : ds.Rows[i][5].ToString().ToDate();
                //    jh.xmjssj = ds.Rows[i][6].ToString().ToDate().Year == 1 ? DateTime.Now : ds.Rows[i][6].ToString().ToDate();
                //    jh.xmztz = ds.Rows[i][7].ToString().ToDecimal();
                //    jh.zjly = ds.Rows[i][8].ToString();

                //    jh.jhnd = ds.Rows[i][8].ToString();
                //    jh.bnjhtzje = ds.Rows[i][9].ToString().ToDecimal();
                //    jh.bnjhapje = ds.Rows[i][10].ToString().ToDecimal();

                //    lists.Add(jh);
                //}

                string strcols = "";
                for (int i = 0; i < ds.Columns.Count; i++)
                {
                    strcols += ds.Columns[i].ColumnName + ",";
                }


                dynamic d = new ExpandoObject();
                d.cols = strcols.TrimEnd(',');
                d.data = ds;

                return Success(d);


            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> ImportTZJHSubmit([FromForm] IFormCollection formCollection, string formcode)
        {
            try
            {

                if (formCollection.Files.Count == 0)
                {
                    return Fail("请上传文件");
                }
                string baseDir = ConfigHelper.GetValue<string>("baseDir");
                FormFileCollection filelist = (FormFileCollection)formCollection.Files;
                string nfilepath = "";
                string oFileName = "";
                foreach (IFormFile file in filelist)
                {
                    String Tpath = "/UpLoad/项目/";
                    oFileName = file.FileName;
                    string FileName = CommonHelper.GetUniqueId().ToString();
                    string FilePath = baseDir + Tpath;

                    string type1 = Path.GetExtension(oFileName);
                    DirectoryInfo di = new DirectoryInfo(FilePath);

                    if (!di.Exists)
                    {
                        di.Create();
                    }

                    using (FileStream fs = System.IO.File.Create(FilePath + FileName + type1))
                    {
                        // 复制文件
                        file.CopyTo(fs);
                        // 清空缓冲区数据
                        fs.Flush();
                    }
                    nfilepath = FilePath + FileName + type1;
                }

                if (string.IsNullOrEmpty(nfilepath))
                {
                    Response.StatusCode = 202;
                    return Fail("请选择上传投资计划数据");
                }

                List<JavaApi.DataItem> listAll = await GetDepInfoList();

                DataTable ds = ExcelHelper.ExcelImport(nfilepath, 1);

                ds.Columns.Add("错误原因");

                bool err = false;

                string jhidc = "";
                for (int i = 0; i < ds.Rows.Count; i++)
                {
                    string tzxm = ds.Rows[i][0].ToString();
                    string czdw = ds.Rows[i][1].ToString();
                    string jsdw = ds.Rows[i][2].ToString();

                    if (string.IsNullOrEmpty(czdw))
                    {
                        err = true;
                        ds.Rows[i]["错误原因"] = "出资单位不能为空";
                    }

                    //if (string.IsNullOrEmpty(jsdw))
                    //{
                    //    err = true;
                    //    ds.Rows[i]["错误原因"] = "建设单位不能为空";
                    //}

                    if (!string.IsNullOrEmpty(tzxm))
                    {
                        //项目不为空，才去判断权限
                        var departInfo = listAll.Find(u => u.name == czdw);
                        //城东街道办事处
                        if (null == departInfo)
                        {
                            err = true;
                            ds.Rows[i]["错误原因"] = "没有该出资单位的权限";
                        }
                        //string strdeptId = departInfo.deptId;

                        jhidc = CommonHelper.GetUniqueId().ToString();
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(jhidc))
                        {
                            ds.Rows[i]["错误原因"] = "该投资方没有关联项目";
                        }
                    }
                }

                if (!err)
                {
                    List<CProTZJH> listjh = new List<CProTZJH>();
                    List<CProTZJHTZF> listtzf = new List<CProTZJHTZF>();
                    List<CProTZJHND> listjz = new List<CProTZJHND>();
                    string jhid = "";
                    for (int i = 0; i < ds.Rows.Count; i++)
                    {
                        string tzxm = ds.Rows[i][0].ToString();

                        if (!string.IsNullOrEmpty(tzxm))
                        {
                            CProTZJH jh = new CProTZJH();
                            jh.id = CommonHelper.GetUniqueId().ToString();

                            //其他投资方 jhid
                            jhid = jh.id;
                            //投资项目名称 出资单位    出资金额 出资比例    投资类型 项目性质    计划开始时间 计划结束时间  项目总投资 资金来源    计划年度 计划投资资金  计划安排资金

                            jh.tzxmmc = ds.Rows[i]["投资项目名称"].ToString();//投资项目
                            //tbdw, fddbr, fddbrsfz, dbr, dbrsfz, lxdh, gslx, shxydm, zczb, clsj, tbsj, tbj
                            jh.tzjhbm = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.投资计划.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(jh), await GetICApiInfo());

                            string jsdw = ds.Rows[i]["建设单位"].ToString();
                            //string jsdw = ds.Rows[i]["建设单位"].ToString();
                            jh.gzdw = (listAll.Find(u => u.name == jsdw)?.deptId ?? "") + " " + jsdw;


                            jh.czdw = ds.Rows[i]["出资单位"].ToString();
                            jh.czje = ds.Rows[i]["出资金额"].ToString().ToDecimal();
                            jh.tzlx = ds.Rows[i]["投资类型"].ToString();
                            jh.xmxz = ds.Rows[i]["项目性质"].ToString();//项目性质

                            //导入的是否补增都是0
                            jh.sfbz = "0";

                            if (ds.Rows[i]["计划开始时间"].ToString().ToDate().Year == 1)
                                jh.xmkssj = null;
                            else
                                jh.xmkssj = ds.Rows[i]["计划开始时间"].ToString().ToDate();

                            if (ds.Rows[i]["计划结束时间"].ToString().ToDate().Year == 1)
                                jh.xmjssj = null;
                            else
                                jh.xmjssj = ds.Rows[i]["计划结束时间"].ToString().ToDate();

                            jh.xmztz = ds.Rows[i]["项目总投资"].ToString().ToDecimal();
                            jh.zjly = ds.Rows[i]["资金来源"].ToString();

                            //JavaApi.DataItem item = await GetDepIDInfoSig(jh.czdw);
                            jh.gsid = listAll.Find(u => u.name == jh.czdw).deptId;

                            listjh.Add(jh);



                            CProTZJHND jhnd = new CProTZJHND();
                            jhnd.id = CommonHelper.GetUniqueId().ToString();
                            jhnd.jhid = jh.id;
                            jhnd.jhnd = ds.Rows[i]["计划年度"].ToString();
                            jhnd.bnjhtzje = ds.Rows[i]["计划投资资金"].ToString().ToDecimal();
                            jhnd.bnjhapje = ds.Rows[i]["计划安排资金"].ToString().ToDecimal();

                            //投资计划审批 还有导入
                            dynamic _dynamic = new ExpandoObject();
                            //_dynamic = jhnd.ToJson().ToJObject();
                            _dynamic.sfbz = "0";

                            var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.投资计划结转.ToString(), jhnd.jhid, jhnd.id);

                            JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = jh.tzjhbm, amount = jhnd.bnjhtzje?.ToString(), content = "[计划结转]" + jhnd.remark1, deptName = GetUserDeptName() };

                            JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.投资计划结转.ToString(), jhnd.id, formcode, Newtonsoft.Json.JsonConvert.SerializeObject(_dynamic), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                            string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());

                            if (strInstanceId.StartsWith("err"))
                            {
                                Response.StatusCode = 202;
                                return Fail("提交失败，启动工作流异常");
                            }

                            jhnd.spl = strInstanceId;
                            jhnd.status = "0";

                            listjz.Add(jhnd);
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(jhid))
                            {
                                CProTZJHTZF tzf = new CProTZJHTZF();
                                tzf.id = CommonHelper.GetUniqueId().ToString();
                                tzf.jhid = jhid;
                                tzf.tzfmc = ds.Rows[i][1].ToString();
                                tzf.tzje = ds.Rows[i][2].ToString().ToDecimal();
                                tzf.tzbl = ds.Rows[i][3].ToString().ToDecimal();
                                listtzf.Add(tzf);
                            }
                        }

                        //lists.Add(jh);
                    }

                    //= await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.投资计划.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(cprotzjh), await GetICApiInfo());


                    if (await CProTZJHRule.GetImportTZJHList(listjh, listjz, listtzf))
                    {
                        //Response.StatusCode = 202;
                        return Success("导入成功");
                    }
                    else
                    {
                        Response.StatusCode = 202;
                        return Fail("导入失败");
                    }
                }
                else
                {
                    //设置导出格式
                    ExcelConfig excelconfig = new ExcelConfig();
                    excelconfig.Title = "年度投资计划";// 文件名称; oFileName.Substring(0, oFileName.LastIndexOf('.'))
                    excelconfig.TitleFont = "微软雅黑";
                    excelconfig.TitlePoint = 25;
                    //excelconfig.HeadPoint = 12;
                    excelconfig.FileName = oFileName;
                    excelconfig.IsAllSizeColumn = true;
                    //每一列的设置,没有设置的列信息，系统将按datatable中的列名导出
                    excelconfig.ColumnEntity = new List<ColumnModel>();
                    for (int i = 0; i < ds.Columns.Count; i++)
                    {
                        excelconfig.ColumnEntity.Add(new ColumnModel() { Column = ds.Columns[i].ColumnName, ExcelColumn = ds.Columns[i].ColumnName });
                    }

                    Response.StatusCode = 201;
                    return File(ExcelHelper.ExportMemoryStream(ds, excelconfig), "application/ms-excel", oFileName.LastIndexOf('.') + ".xls");
                }
            }
            catch (Exception ex)
            {
                Response.StatusCode = 202;
                return Fail(ex.Message);
            }
        }
        #endregion

        #region 导出

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> ExportList(dynamic expjson)
        {

            JObject job = (JObject)expjson;

            List<string> ids = new List<string>();
            List<ColumnModel> cols = new List<ColumnModel>();

            if (null != job["ids"])
                ids = job["ids"].ToObject<string[]>().ToList();

            if (null != job["cols"])
                cols = job["cols"].ToObject<ColumnModel[]>().ToList();

            return File(await CProTZJHRule.GetExportList(ids, cols, BaseEditPower.TableName.投资计划结转, "投资计划列表"), "application/ms-excel", "投资计划列表.xls");
        }

        #endregion

        #region 审批流回调状态

        [HttpPost]
        public async Task<IActionResult> UpdateStatus(dynamic spjson)//
        {

            //module，dealUser，approveStatus，businessName，businessId
            try
            {
                _logger.Debug(JsonConvert.SerializeObject(spjson));

                //{
                //    "businessId":"1403255058317729793",
                //    "businessName":"quotaDetailServiceImpl",
                //    "opinion":"合格，通过，批钱",
                //    "instanceId":352926,
                //    "taskId":352983
                //}
                //string taskId = spjson.taskId;
                //string businessName = spjson.businessName;
                //string instanceId = spjson.instanceId;

                string moduleid = spjson.module;
                string userid = spjson.dealUser;
                string approveStatus = spjson.approveStatus;//UNCHECK, CHECKING,REJECTED,INVALID,CHECKED,HANDEL

                //operation，值：AGREE（同意），REJECT（驳回），INVALID（作废），ACTIVATION（激活），CANCEL（撤销），RESTART（消审）
                string operation = spjson.operation;
                string businessId = spjson.businessId;
                string businessName = spjson.businessName;

                string additionInfo = spjson.additionInfo;

                //additionInfo： {
                //    sdje
                //    ywid
                //    tname
                //  }


                //这里加了一个审定金额
                string sdje = "";

                try
                {
                    if (!string.IsNullOrEmpty(additionInfo))
                    {
                        var addi = additionInfo.ToObject<dynamic>();

                        sdje = addi.sdje;

                    }
                }
                catch
                {

                }


                if (string.IsNullOrEmpty(businessId))
                {
                    //return Fail("业务id不能为空");
                    return Json(new ResParameter { code = ResponseCode.fail, message = "业务id不能为空" });
                }

                //待提交  未审核  审核中  作废  已审核  驳回
                //DRAFT  UNCHECK, CHECKING,INVALID,CHECKED
                string ztz = CProTZJHRule.GetXMGLSPZT(approveStatus);

                if (operation == "RESTART")//消审以后
                {
                    ztz = "-1";//未提交的状态
                }

                string strTname = businessName;

                //if (await BaseEditPower.GetEditPowerOpe(businessId, strTname, ztz))
                //{

                //}
                //else
                //{
                //    return Fail("请确认当前数据权限状态");
                //}


                if (BaseEditPower.TableName.结算.ToString() == strTname)
                {
                    string sjdw = "";
                    if (!string.IsNullOrEmpty(additionInfo))
                    {
                        var addi = additionInfo.ToObject<dynamic>();
                        sjdw = addi.sjdw;
                    }

                    if (ztz == "2")
                    {
                        CProJS js = await ProJunGongRule.GetJSTableByid(businessId);
                        string tsjdw = js?.sjdw ?? "";
                        if (string.IsNullOrEmpty(tsjdw) && string.IsNullOrEmpty(sjdw))
                        {
                            return Json(new ResParameter { code = ResponseCode.fail, message = "操作失败,终审审计单位不能为空" });
                        }
                    }
                }

                await BaseEditPower.SetStatus(businessId, strTname, ztz, GetUserName(), userid, CommonHelper.ParseDecimal(sdje), additionInfo);

                #region 加日志
                LogEntity logEntity = new LogEntity();
                logEntity.F_CategoryId = 3;
                logEntity.F_OperateTypeId = ((int)OperationType.Audit).ToString();
                logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Audit);
                logEntity.F_OperateAccount = ContextHelper.GetItem("userName") as string;
                logEntity.F_OperateUserId = ContextHelper.GetItem("userId") as string;
                logEntity.F_Module = Request.Path;
                logEntity.F_IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                logEntity.F_ExecuteResult = -1;
                var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
                logEntity.F_ExecuteResultJson = JsonConvert.SerializeObject(spjson, timeConverter);
                //添加日志
                await LogRule.Write(logEntity);
                #endregion

                return Json(new ResParameter { code = ResponseCode.success, message = "成功" });
            }
            catch (Exception ex)
            {
                return Json(new ResParameter { code = ResponseCode.fail, message = "操作失败" + ex.Message });
            }
        }

        #endregion

        #region 投资计划

        /// <summary>
        /// 查询 计划列表
        [HttpGet]
        [XMZCAuthorizeAttribute()]//"GetTZJHList", "GetTZJHList"
        //string formCode, string tzxmmc, string tzjhbm, string tzlx, string tzxz, string xmxz, string xmgldw, string xmcqdw, string czdw, string yearRange, string status,string sfbz, string current = "1", string size = "20", string sort = "desc", string column = "id"
        public async Task<IActionResult> GetTZJHList([FromQuery] CProTZJHQuerry querry)
        {
            try
            {
                (IEnumerable<dynamic>, int) SelectTable = await CProTZJHRule.GetTZJHList(querry, querry.formCode, await GetDepId());

                if (!string.IsNullOrEmpty(querry.formCode))
                {
                    List<string> list = new List<string>();
                    foreach (dynamic item in SelectTable.Item1)
                    {
                        //这里是id
                        string id = item.jhndid;

                        list.Add(id);
                    }


                    if (querry.formCode == "investment_modify_attach")
                    {
                        querry.formCode = "investment_plan_attach";
                    }

                    List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(querry.formCode, GetUserAccount(), list, await GetICApiInfo());
                    foreach (dynamic item in SelectTable.Item1)
                    {
                        string id = item.jhndid;

                        var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();
                        item.panguData = GetPanGudData(spstatus, item.spstatus);
                        //if (null != spstatus)
                        //    item.panguData = GetPanGudData(spstatus, item.spstatus);
                        //else
                        //    item.panguData = new JavaApi.panguData() { reviewStatus = item.spstatus };
                    }
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;

                return Success(pa);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                return Fail("响应失败:" + ex);
            }
        }

        //做计划变更时选择弹窗
        [HttpGet]
        [XMZCAuthorizeAttribute()]//"GetTZJHList", "GetTZJHList"
        public async Task<IActionResult> GetXZTZJHList(string formCode, string tzxmmc, string tzjhbm, string tzlx, string tzxz, string xmxz, string xmgldw, string xmcqdw, string czdw, string yearRange, string status, string current = "1", string size = "20", string sort = "desc", string column = "id")
        {
            //string str = "11".Substring(10,2); ;
            try
            {
                CProTZJHQuerry querry = new CProTZJHQuerry();
                //基础属性
                querry.size = CommonHelper.ParseInt(size);
                querry.current = CommonHelper.ParseInt(current);
                querry.sort = sort;
                querry.column = column;


                querry.tzxmmc = tzxmmc;
                querry.tzjhbm = tzjhbm;
                querry.tzxz = tzxz;
                querry.xmxz = xmxz;

                querry.tzlx = tzlx;

                querry.xmgldw = xmgldw;
                querry.xmcqdw = xmcqdw;
                querry.czdw = czdw;

                querry.kssj = yearRange;

                querry.status = status;

                querry.kyje = "1";

                (IEnumerable<dynamic>, int) SelectTable = await CProTZJHRule.GetTZJHList(querry, formCode, await GetDepId());

                if (!string.IsNullOrEmpty(formCode))
                {
                    List<string> list = new List<string>();
                    foreach (dynamic item in SelectTable.Item1)
                    {
                        //这里是id
                        string id = item.jhndid;

                        list.Add(id);
                    }


                    if (formCode == "investment_modify_attach")
                    {
                        formCode = "investment_plan_attach";
                    }

                    List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(formCode, GetUserAccount(), list, await GetICApiInfo());
                    foreach (dynamic item in SelectTable.Item1)
                    {
                        string id = item.jhndid;

                        var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();
                        item.panguData = GetPanGudData(spstatus, item.spstatus);
                        //if (null != spstatus)
                        //    item.panguData = GetPanGudData(spstatus, item.spstatus);
                        //else
                        //    item.panguData = new JavaApi.panguData() { reviewStatus = item.spstatus };
                    }
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;

                return Success(pa);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                return Fail("响应失败:" + ex);
            }
        }


        //弹窗选择
        [HttpPost]
        //[AllowAnonymous]
        //[XMZCAuthorizeAttribute()]//"GetTZJHList", "GetTZJHList"
        public async Task<IActionResult> GetTZJHListByids(List<string> ids)
        {
            try
            {
                var rest = await CProTZJHRule.GetTZJHList1(ids, await GetDepId());
                return Success(rest);
            }
            catch (Exception ex)
            {
                return Fail("响应失败");
            }

        }



        /// <summary>
        /// 获取结转列表
        /// </summary>
        /// <param name="tzjhid"></param>
        /// <returns></returns>
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetTZJHListByid(string tzjhid)//
        {
            try
            {
                var SelectTable = await CProTZJHRule.GetTZJHList(tzjhid);

                //添加其他投资方
                SelectTable.tzjhtzf = await CProTZJHRule.GetTZJHTZFList(tzjhid);

                //结转信息
                SelectTable.tzjhnd = await CProTZJHRule.GetTZJHJZList(tzjhid);

                return Success(SelectTable);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

        /// <summary>
        /// 新增修改投资计划
        /// </summary>
        /// <param name="cprotzjh"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> InsertCProTZJH(dynamic cprotzjh)//
        {

            #region 投资计划
            //          {
            //              "ope": "add",
            //"tzjh": {
            //                  "id": "1",
            //  "tzxmmc": "string",
            //  "tzjhbm": "string",
            //  "gzdw": "string",
            //  "czdw": "string",
            //  "czje": 0,
            //  "tzlx": "string",
            //  "xmxz": "string",
            //  "xmgm": "string",
            //  "xmgldw": "string",
            //  "xmcqdw": "string",
            //  "xmkssj": "2021-05-13T00:43:37.723Z",
            //  "xmjssj": "2021-05-13T00:43:37.723Z",
            //  "xmgq": 0,
            //  "xmztz": 0,
            //  "tzxz": "string",
            //  "zjly": "string",
            //  "tzjhsm": "string",
            //  "xmjsnr": "string",
            //  "remark1": "string",
            //  "remark2": "string",
            //  "createdate": "2021-05-13T00:43:37.723Z",
            //  "createuser": "string",
            //  "spl": "string",
            //  "status": "string",
            //  "gsid": "string"
            //},
            //"tzjhtzf": [
            //  {
            //                  "id": "string",
            //    "jhid": "1",
            //    "tzfmc": "string",
            //    "dwxz": "string",
            //    "tzje": 0,
            //    "tzbl": 0,
            //    "reamrk1": "string",
            //    "remark2": "string",
            //    "createdate": "2021-05-13T00:43:37.723Z",
            //    "createuser": "string"
            //  }
            //],
            //"tzjhnd": {
            //                  "id": "string",
            //  "jhid": "1",
            //  "jhnd": "string",
            //  "bnjhtzje": 0,
            //  "bnjhapje": 0,
            //  "jzje": 0,
            //  "remark1": "string",
            //  "remark2": "string",
            //  "createuser": "string",
            //  "createdate": "2021-05-13T00:43:37.723Z",
            //  "spl": "string",
            //  "status": "string"
            //},
            //"filecodes":["1","2"]
            //          }

            #endregion

            string strope = "add";
            CProTZJH tzjh = new CProTZJH();
            CProTZJHND tzjhnd = new CProTZJHND();
            List<CProTZJHTZF> tzjhtzf = new List<CProTZJHTZF>();
            //添加附件上传
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)cprotzjh;

                //获取方法
                strope = cprotzjh.ope;
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                tzjh = job["tzjh"].ToObject<CProTZJH>();
                if (null != job["tzjhnd"])
                    tzjhnd = job["tzjhnd"].ToObject<CProTZJHND>();
                if (null != job["tzjhtzf"])
                    tzjhtzf = job["tzjhtzf"].ToObject<CProTZJHTZF[]>().ToList();

                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();


                if (strope != "add" && strope != "edit" && strope != "del" && strope != "submit")
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }

            try
            {
                string strlsope = strope;
                if (strope == "submit")
                {
                    if (string.IsNullOrEmpty(tzjh.id))//完成新增
                    {
                        strope = "add";
                    }
                    else
                    {
                        CProTZJH jhe = await TranstionRule.FindEntityByKey<CProTZJH>(tzjh.id);
                        if (null == jhe)
                        {
                            strope = "add";
                        }
                        else
                        {
                            strope = "edit";
                        }
                    }
                    tzjh.status = BaseEditPower.GetSPEnumValue("待审核");
                    tzjhnd.status = BaseEditPower.GetSPEnumValue("待审核");


                    if (string.IsNullOrEmpty(tzjh.tzxmmc))
                    {
                        return Fail("投资项目名称不能为空");
                    }
                    //if (string.IsNullOrEmpty(tzjh.tzjhbm))
                    //{
                    //    return Fail("投资计划编码不能为空");
                    //}
                    if (tzjh.xmkssj.Value.Year == 1900)//tzjh.xmkssj.Value.Year == 1900
                    {
                        return Fail("计划开始时间不能为空");
                    }
                    //if (string.IsNullOrEmpty(tzjh.zjly))
                    //{
                    //    return Fail("资金来源不能为空");
                    //}

                }



                if (string.IsNullOrEmpty(tzjh.gsid))
                {
                    return Fail("投资计划gsid不能为空");
                }

                if (strope == "edit" || strope == "del")
                {
                    if (string.IsNullOrEmpty(tzjh.id))
                    {
                        return Fail("投资计划id不能为空");
                    }

                    CProTZJHND minnd = await CProTZJHRule.GetTZJHNDidMin(tzjh.id);
                    if (null != minnd)
                    {
                        if (!await BaseEditPower.GetEditPower(minnd.id, BaseEditPower.TableName.投资计划结转))
                        {
                            return Fail("请确认当前数据权限状态");
                        }
                    }
                }
                if (strope == "add")
                {
                    tzjh.id = CommonHelper.GetUniqueId().ToString();
                    tzjh.createuser = GetUserName();

                    tzjh.tzjhbm = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.投资计划.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(cprotzjh), await GetICApiInfo());

                    tzjhnd.id = CommonHelper.GetUniqueId().ToString();


                    //tzjh.gsid = ContextHelper.deptId();//GetItem("deptId").ToString()

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(tzjh.id, filecodes, await GetICApiInfo());

                    if (strlsope != "submit")
                    {
                        tzjh.status = BaseEditPower.GetSPEnumValue("待提交");
                        tzjhnd.status = BaseEditPower.GetSPEnumValue("待提交");
                    }

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        //投资计划审批 还有导入
                        dynamic _dynamic = new ExpandoObject();
                        _dynamic.sfbz = tzjh.sfbz;


                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.投资计划.ToString(), tzjh.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = tzjh.tzjhbm, amount = tzjh.xmztz?.ToString(), content = "[投资计划]" + tzjh.tzxmmc, deptName = GetUserDeptName() };

                        //cprotzjh
                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.投资计划结转.ToString(), tzjhnd.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(_dynamic), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                        tzjhnd.spl = strInstanceId;
                    }

                    await CProTZJHRule.InsertTZJH(tzjh, tzjhnd, tzjhtzf, strope, GetUserName());

                }
                else if (strope == "edit")
                {
                    //
                    if (string.IsNullOrEmpty(tzjhnd.jhnd))
                    {
                        return Fail("投资计划年度不能为空");
                    }

                    tzjhnd.id = CommonHelper.GetUniqueId().ToString();


                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(tzjh.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        //投资计划审批 还有导入
                        dynamic _dynamic = new ExpandoObject();
                        _dynamic.sfbz = tzjh.sfbz;

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.投资计划.ToString(), tzjh.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = tzjh.tzjhbm, amount = tzjh.xmztz?.ToString(), content = "[投资计划]" + tzjh.tzxmmc, deptName = GetUserDeptName() };

                        //cprotzjh
                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.投资计划结转.ToString(), tzjhnd.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(_dynamic), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);

                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        //{
                        //    return Fail("提交失败，启动工作流异常");
                        //}
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                        tzjhnd.spl = strInstanceId;
                    }
                    await CProTZJHRule.InsertTZJH(tzjh, tzjhnd, tzjhtzf, strope, GetUserId());

                }
                else if (strope == "del")
                {
                    //新增投资计划
                    await CProTZJHRule.DeleteTZJH(tzjh.id, GetUserId());
                }


                return Success("成功");
            }
            catch (Exception ex)
            {
                //_logger.Log(LogLevel.Info, this.Url.Action() + zc.ToJson());
                _logger.Error(ex.Message);
                return Fail("响应失败:" + ex.Message);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> DelCProTZJH(Root ids)
        {
            try
            {
                //JObject job = (JObject)cprotzjh;

                foreach (BaseDeleteMulti idm in ids.ids)
                {
                    if (string.IsNullOrEmpty(idm.id))
                    {
                        return Fail("需要删除的计划编号不能为空");
                    }

                    CProTZJHND minnd = await CProTZJHRule.GetTZJHNDidMin(idm.id);
                    if (null != minnd)
                    {
                        if (!await BaseEditPower.GetEditPower(minnd.id, BaseEditPower.TableName.投资计划结转))
                        {
                            return Fail("响应失败:请确认数据权限");
                        }
                    }

                    //if (!await BaseEditPower.GetEditPower(idm.id, BaseEditPower.TableName.投资计划))
                    //{
                    //    return Fail("响应失败:请确认数据权限");
                    //}
                }
            }
            catch (Exception ex)
            {
                return Fail("出错：" + ex.Message);
            }

            try
            {

                //新增投资计划
                await CProTZJHRule.DeleteTZJH(ids, GetUserId());

                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }
        #endregion

        #region 投资计划结转
        /// <summary>
        /// 查询 计划列表
        /// 
        ///
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetTZJHJZList(string formCode, string tzxmmc, string jhnd, string tzlx, string tzxz, string xmxz, string xmcqdw, string czdw, string jsdw, string status, string year, string sfjz, string current = "1", string size = "20", string sort = "desc", string column = "id")
        {
            //string str = "11".Substring(10,2); ;
            try
            {
                CProTZJHQuerry querry = new CProTZJHQuerry();
                //基础属性
                querry.size = CommonHelper.ParseInt(size);
                querry.current = CommonHelper.ParseInt(current);
                querry.sort = sort;
                querry.column = column;

                querry.jhnd = jhnd;
                querry.tzxmmc = tzxmmc;

                querry.tzxz = tzxz;
                querry.tzlx = tzlx;
                querry.xmxz = xmxz;

                querry.czdw = czdw;
                querry.jsdw = jsdw;

                querry.status = status;
                querry.sfjz = sfjz;

                querry.yearRange = year;

                (IEnumerable<dynamic>, int) SelectTable = await CProTZJHRule.GetTZJHJZList(querry, formCode, await GetDepId());

                if (!string.IsNullOrEmpty(formCode))
                {
                    List<string> list = new List<string>();
                    foreach (dynamic item in SelectTable.Item1)
                    {
                        //这里是id
                        string id = item.id;

                        list.Add(id);
                    }


                    List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(formCode, GetUserAccount(), list, await GetICApiInfo());
                    foreach (dynamic item in SelectTable.Item1)
                    {
                        string id = item.id;

                        var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();
                        item.panguData = GetPanGudData(spstatus, item.spstatus);
                        //if (null != spstatus)
                        //    item.panguData = GetPanGudData(spstatus, item.spstatus);
                        //else
                        //    item.panguData = new JavaApi.panguData() { reviewStatus = item.spstatus };
                    }
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;

                return Success(pa);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                return Fail("响应失败:" + ex);
            }
        }

        /// <summary>
        /// 获取结转列表
        /// </summary>
        /// <param name="tzjhid"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> GetTZJHJZList(string tzjhid)//
        {
            try
            {
                DataTable SelectTable = await CProTZJHRule.GetTZJHJZList(tzjhid);
                Page pa = new Page();
                //pa.records = SelectTable.Item1;
                //pa.total = SelectTable.Item2;
                return Success(SelectTable);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

        /// <summary>
        /// 根据结转id获取结转数据
        /// </summary>
        /// <param name="jzid"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> GetTZJHJZEntity(string jzid)//
        {
            try
            {
                var SelectTable = await CProTZJHRule.GetTZJHJZEntity(jzid);

                try
                {
                    if (null != SelectTable)
                        SelectTable.forwardinfo = await CProTZJHRule.GetTZJHJZBefourEntity(jzid);
                }
                catch
                {
                }

                return Success(SelectTable);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

        /// <summary>
        /// 新增投资计划结转
        /// </summary>
        /// <param name="tzjhjz"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> InsertTZJHJZ(dynamic tzjhjz)//
        {
            string strope = "add";

            CProTZJHND tzjhnd = new CProTZJHND();

            //添加附件上传
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)tzjhjz;

                //获取方法
                strope = tzjhjz.ope;
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                if (null != job["tzjhnd"])
                    tzjhnd = job["tzjhnd"].ToObject<CProTZJHND>();
                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();


                if (strope != "add" && strope != "edit" && strope != "submit")
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }

            try
            {

                if (string.IsNullOrEmpty(tzjhnd.jhid))
                {
                    return Fail("投资计划编号不能为空");
                }
                if (string.IsNullOrEmpty(tzjhnd.jhnd))
                {
                    return Fail("投资计划年度不能为空");
                }

                string strlsope = strope;
                if (strope == "submit")
                {
                    if (string.IsNullOrEmpty(tzjhnd.id))//完成新增
                    {
                        strope = "add";
                    }
                    else
                    {
                        CProTZJHND jhe = await TranstionRule.FindEntityByKey<CProTZJHND>(tzjhnd.id);
                        if (null == jhe)
                        {
                            strope = "add";
                        }
                        else
                        {
                            strope = "edit";
                        }
                    }
                    tzjhnd.status = BaseEditPower.GetSPEnumValue("待审核");
                }
                else if (strope == "add")
                {
                    CProTZJHND jhe = await TranstionRule.FindEntity<CProTZJHND>(new { jhid = tzjhnd.jhid, jhnd = tzjhnd.jhnd });
                    if (null != jhe)
                    {
                        if (!await BaseEditPower.GetEditPower(jhe.id, BaseEditPower.TableName.投资计划结转))
                        {
                            return Fail("请确认当前数据权限状态");
                        }

                        tzjhnd.id = jhe.id;

                        strope = "edit";
                    }
                }

                if (strope == "add")
                {


                    tzjhnd.id = CommonHelper.GetUniqueId().ToString();

                    if (strlsope != "submit")
                    {
                        tzjhnd.status = BaseEditPower.GetSPEnumValue("待提交");
                    }



                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(tzjhnd.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        CProTZJH jhe = await TranstionRule.FindEntity<CProTZJH>(new { id = tzjhnd.jhid });
                        if (null == jhe)
                        {
                            return Fail("根据jhid未检索到投资计划信息");
                        }

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.投资计划结转.ToString(), tzjhnd.jhid, tzjhnd.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = jhe.tzjhbm, amount = tzjhnd.bnjhtzje?.ToString(), content = "[计划结转]" + tzjhnd.remark1, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.投资计划结转.ToString(), tzjhnd.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(tzjhjz), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        tzjhnd.spl = strInstanceId;

                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }

                    }


                    //新增投资计划
                    await CProTZJHRule.InsertTZJHJZ(tzjhnd, GetUserId());
                }
                else if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(tzjhnd.id))
                    {
                        return Fail("投资计划结转编号不能为空");
                    }

                    if (!await BaseEditPower.GetEditPower(tzjhnd.id, BaseEditPower.TableName.投资计划结转))
                    {
                        return Fail("请确认当前数据权限状态");
                    }



                    ////这里先绑定附件
                    //await JavaApi.UploadFileJavaAPI(tzjhnd.id, filecodes, await GetICApiInfo());
                    ////新增投资计划
                    //await CProTZJHRule.UpdateTZJHJZ(tzjhnd, GetUserId());

                    if (strlsope != "submit")
                    {
                        tzjhnd.status = BaseEditPower.GetSPEnumValue("待提交");
                    }

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(tzjhnd.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;


                        CProTZJH jhe = await TranstionRule.FindEntity<CProTZJH>(new { id = tzjhnd.jhid });
                        if (null == jhe)
                        {
                            return Fail("根据jhid未检索到投资计划信息");
                        }

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.投资计划结转.ToString(), tzjhnd.jhid, tzjhnd.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = jhe.tzjhbm, amount = tzjhnd.bnjhtzje?.ToString(), content = "[计划结转]" + tzjhnd.remark1, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.投资计划结转.ToString(), tzjhnd.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(tzjhjz), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        //if (!bsp)
                        tzjhnd.spl = strInstanceId;

                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }
                    await CProTZJHRule.UpdateTZJHJZ(tzjhnd, GetUserId());
                }



                return Success("成功");
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                return Fail("响应失败:" + ex.Message);
            }
        }

        /// <summary>
        /// 修改投资计划结转
        /// </summary>
        /// <param name="tzjhjz"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> UpdateTZJHJZ(CProTZJHND tzjhjz)//
        {
            try
            {
                if (string.IsNullOrEmpty(tzjhjz.id))
                {
                    return Fail("投资计划结转编号不能为空");
                }
                if (string.IsNullOrEmpty(tzjhjz.jhid))
                {
                    return Fail("投资计划编号jhid不能为空");
                }
                if (string.IsNullOrEmpty(tzjhjz.jhnd))
                {
                    return Fail("投资计划年度不能为空");
                }



                if (!await BaseEditPower.GetEditPower(tzjhjz.id, BaseEditPower.TableName.投资计划结转))
                {
                    return Fail("请确认当前数据权限状态");
                }

                //新增投资计划
                await CProTZJHRule.UpdateTZJHJZ(tzjhjz, GetUserId());

                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }

        /// <summary>
        /// 删除结转
        /// </summary>
        /// <param name="jzid"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> DelTZJHJZ(string jzid)//
        {
            try
            {
                if (string.IsNullOrEmpty(jzid))
                {
                    return Fail("投资计划结转编号不能为空");
                }

                if (!await BaseEditPower.GetEditPower(jzid, BaseEditPower.TableName.投资计划结转))
                {
                    return Fail("响应失败:请确认数据权限");
                    //throw new Exception("请确认数据权限");
                }


                //新增投资计划
                await CProTZJHRule.DeleteTZJHJZ(jzid, GetUserId());

                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }
        #endregion

        #region 投资计划变更
        /// <summary>
        /// 查询 计划列表
        /// 
        ///
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetTZJHBGIndexList(string formCode, string tzxmmc, string year, string tzlx, string tzxz, string xmcqdw, string czdw, string status, string current = "1", string size = "20", string sort = "desc", string column = "id")
        {
            //string str = "11".Substring(10,2); ;
            try
            {
                CProTZJHQuerry querry = new CProTZJHQuerry();
                //基础属性
                querry.size = CommonHelper.ParseInt(size);
                querry.current = CommonHelper.ParseInt(current);
                querry.sort = sort;
                querry.column = column;

                querry.jhnd = year;
                querry.tzxmmc = tzxmmc;

                querry.tzxz = tzxz;
                querry.tzlx = tzlx;

                querry.czdw = czdw;

                querry.status = status;

                (IEnumerable<dynamic>, int) SelectTable = await CProTZJHRule.GetTZJHBGIndexList(querry, formCode, await GetDepId());

                if (!string.IsNullOrEmpty(formCode))
                {
                    List<string> list = new List<string>();
                    foreach (dynamic item in SelectTable.Item1)
                    {
                        //这里是id
                        string id = item.id;

                        list.Add(id);
                    }


                    List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(formCode, GetUserAccount(), list, await GetICApiInfo());
                    foreach (dynamic item in SelectTable.Item1)
                    {
                        string id = item.id;

                        var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();
                        item.panguData = GetPanGudData(spstatus, item.spstatus);
                        //if (null != spstatus)
                        //    item.panguData = GetPanGudData(spstatus, item.spstatus);
                        //else
                        //    item.panguData = new JavaApi.panguData() { reviewStatus = item.spstatus };
                    }
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;

                return Success(pa);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                return Fail("响应失败:" + ex);
            }
        }

        /// <summary>
        /// 获取计划变更列表
        /// </summary>
        /// <param name="tzjhid"></param>
        /// <returns></returns>
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetTZJHBGListByjhid(string tzjhid)//根据计划id获取变更列表
        {
            try
            {
                DataTable SelectTable = await CProTZJHRule.GetTZJHBGListByjhid(tzjhid);
                //Page pa = new Page();
                //pa.records = SelectTable.Item1;
                //pa.total = SelectTable.Item2;
                return Success(SelectTable);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

        /// <summary>
        /// 获取计划结转变更列表
        /// </summary>
        /// <param name="tzjhid"></param>
        /// <returns></returns>
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetTZJHBGListByjzid(string jzid)//根据计划id获取变更列表
        {
            try
            {
                DataTable SelectTable = await CProTZJHRule.GetTZJHBGListByjzid(jzid);
                //Page pa = new Page();
                //pa.records = SelectTable.Item1;
                //pa.total = SelectTable.Item2;
                return Success(SelectTable);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

        /// <summary>
        /// 获取计划变更列表
        /// </summary>
        /// <param name="tzjhjzid"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> GetTZJHBGList(string tzjhjzid)//根据结转id获取变更列表
        {
            try
            {
                DataTable SelectTable = await CProTZJHRule.GetTZJHBGList(tzjhjzid);
                //Page pa = new Page();
                //pa.records = SelectTable.Item1;
                //pa.total = SelectTable.Item2;
                return Success(SelectTable);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

        /// <summary>
        /// 获取计划变更列表
        /// </summary>
        /// <param name="bgid"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> GetTZJHBGEntity(string bgid)//根据变更id获取变更列表
        {
            try
            {
                var SelectTable = await CProTZJHRule.GetTZJHBGByid(bgid);
                //Page pa = new Page();
                //pa.records = SelectTable.Item1;
                //pa.total = SelectTable.Item2;
                return Success(SelectTable);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

        /// <summary>
        /// 新增投资计划变更
        /// </summary>
        /// <param name="tzjhbgs"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> InsertTZJHBG(dynamic tzjhbgs)//string strlx = "xxx"
        {

            string strope = "add";

            CProTZJHbgS tzjhbg = new CProTZJHbgS();

            //添加附件上传
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)tzjhbgs;

                //获取方法
                strope = tzjhbgs.ope;
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                if (null != job["tzjhbg"])
                    tzjhbg = job["tzjhbg"].ToObject<CProTZJHbgS>();

                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();

                //&& strope != "del"
                if (strope != "add" && strope != "edit" && strope != "submit" && strope != "approved")
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }

            try
            {
                string strlsope = strope;
                if (strope == "submit")
                {
                    if (string.IsNullOrEmpty(tzjhbg.id))//完成新增
                    {
                        strope = "add";
                    }
                    else
                    {
                        CProTZJHbgS jhe = await TranstionRule.FindEntityByKey<CProTZJHbgS>(tzjhbg.id);
                        if (null == jhe)
                        {
                            strope = "add";
                        }
                        else
                        {
                            strope = "edit";
                        }
                    }
                    tzjhbg.status = BaseEditPower.GetSPEnumValue("待审核");
                }

                if (strope == "add")
                {
                    if (string.IsNullOrEmpty(tzjhbg.jhndid))
                    {
                        return Fail("投资计划年度编号不能为空");
                    }
                    decimal dsqje = tzjhbg.sqje ?? 0;
                    if (dsqje == 0)
                    {
                        return Fail("变更申报金额不能为空或零");
                    }
                    if (string.IsNullOrEmpty(tzjhbg.bgmc))
                    {
                        return Fail("变更名称不能为空");
                    }


                    //重新赋值一个新id
                    tzjhbg.id = CommonHelper.GetUniqueId().ToString();
                    if (strlsope != "submit")
                        tzjhbg.status = BaseEditPower.GetSPEnumValue("待提交");

                    tzjhbg.bgbm = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.投资计划变更.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(tzjhbgs), await GetICApiInfo());
                    tzjhbg.createuser = GetUserName();
                    tzjhbg.createdate = DateTime.Now;

                    //tzjhbg.ljbgbl = 
                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(tzjhbg.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;



                        dynamic _dynamic = new ExpandoObject();
                        _dynamic.sqje = tzjhbg.sqje;

                        CProTZJHND jhe = await TranstionRule.FindEntityByKey<CProTZJHND>(tzjhbg.jhndid);

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.投资计划变更.ToString(), jhe.jhid, tzjhbg.jhndid, tzjhbg.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = tzjhbg.bgbm, amount = tzjhbg.sqje?.ToString(), content = "[计划变更]" + tzjhbg.bgmc, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.投资计划变更.ToString(), tzjhbg.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(_dynamic), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);

                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());

                        tzjhbg.spl = strInstanceId;
                        //if (!bsp)
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    //新增投资计划
                    await CProTZJHRule.InsertTZJHBG(tzjhbg, GetUserId());
                }
                if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(tzjhbg.id))
                    {
                        return Fail("投资计划变更编号不能为空");
                    }
                    if (string.IsNullOrEmpty(tzjhbg.jhndid))
                    {
                        return Fail("投资计划年度编号不能为空");
                    }
                    if (tzjhbg.sqje == 0)
                    {
                        return Fail("变更金额不能为空或零");
                    }


                    if (!await BaseEditPower.GetEditPower(tzjhbg.id, BaseEditPower.TableName.投资计划变更))
                    {
                        return Fail("响应失败:请确认数据权限");
                    }

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(tzjhbg.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    string strspl = "";
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        //CProTZJHbgS jhe = await TranstionRule.FindEntityByKey<CProTZJHbgS>(tzjhbg.id);
                        //if (null == jhe)
                        //{
                        //    return Fail("根据id未检索到投资计划变更信息");
                        //}

                        dynamic _dynamic = new ExpandoObject();
                        _dynamic.sqje = tzjhbg.sqje;

                        CProTZJHND jhe = await TranstionRule.FindEntityByKey<CProTZJHND>(tzjhbg.jhndid);
                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.投资计划变更.ToString(), jhe.jhid, tzjhbg.jhndid, tzjhbg.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = tzjhbg.bgbm, amount = tzjhbg.sqje?.ToString(), content = "[计划变更]" + tzjhbg.bgmc, deptName = GetUserDeptName() };
                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.投资计划变更.ToString(), tzjhbg.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(_dynamic), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());

                        tzjhbg.spl = strInstanceId;

                        //if (strspl.Contains("err"))
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }

                        tzjhbg.spl = strspl;
                    }

                    //新增投资计划
                    await CProTZJHRule.UpdateTZJHBG(tzjhbg, GetUserId());
                }
                else if (strope == "approved")
                {
                    if (string.IsNullOrEmpty(tzjhbg.id))
                    {
                        return Fail("投资计划变更编号不能为空");
                    }
                    if (tzjhbg.bgsdje == 0)
                    {
                        return Fail("变更审定金额不能为空或零");
                    }

                    //变更签证编码
                    if (string.IsNullOrEmpty(tzjhbg.bgqzbh))
                    {
                        tzjhbg.bgqzbh = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.投资计划变更.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(tzjhbgs), await GetICApiInfo());
                    }


                    //var dts = await CProTZJHRule.GetTZJHBGByid(tzjhbg.id);
                    //string strstatus = "";
                    //if (null != dts)
                    //{
                    //    strstatus = dts.st
                    //}
                    //for (int i = 0; i < dts.Rows.Count; i++)
                    //{
                    //    strstatus = dts.Rows[i]["status"].ToString();
                    //}
                    string strstatus = "";
                    CProTZJHbgS jhe = await TranstionRule.FindEntityByKey<CProTZJHbgS>(tzjhbg.id);
                    if (null != jhe)
                    {
                        strstatus = jhe.status;
                    }

                    if (strstatus == "2")
                    {

                        //这里先绑定附件
                        await JavaApi.UploadFileJavaAPI(tzjhbg.id, filecodes, await GetICApiInfo());

                        //新增投资计划
                        await CProTZJHRule.UpdateTZJHBG(tzjhbg, GetUserId());
                    }
                    else
                    {
                        return Fail("数据状态为" + strstatus + ",未审核完成");
                    }
                }


                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }

        /// <summary>
        /// 修改投资计划变更
        /// </summary>
        /// <param name="tzjhbg"></param>
        /// <param name="strlx"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> UpdateTZJHBG(CProTZJHbgS tzjhbg, string strlx = "xxx")//
        {
            try
            {
                string strope = strlx.ToLower();
                if (strope != "edit" && strope != "approved")
                {
                    return Fail("strlx参数错误");
                }

                if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(tzjhbg.id))
                    {
                        return Fail("投资计划变更编号不能为空");
                    }
                    if (string.IsNullOrEmpty(tzjhbg.jhndid))
                    {
                        return Fail("投资计划年度编号不能为空");
                    }
                    if (tzjhbg.sqje == 0)
                    {
                        return Fail("变更金额不能为空或零");
                    }


                    if (!await BaseEditPower.GetEditPower(tzjhbg.id, BaseEditPower.TableName.投资计划变更))
                    {
                        return Fail("响应失败:请确认数据权限");
                    }

                    //新增投资计划
                    await CProTZJHRule.UpdateTZJHBG(tzjhbg, GetUserId());
                }
                else if (strope == "approved")
                {
                    if (string.IsNullOrEmpty(tzjhbg.id))
                    {
                        return Fail("投资计划变更编号不能为空");
                    }
                    if (tzjhbg.bgsdje == 0)
                    {
                        return Fail("变更审定金额不能为空或零");
                    }
                    DataTable dts = await CProTZJHRule.GetTZJHBGByid(tzjhbg.id);
                    string strstatus = "";
                    for (int i = 0; i < dts.Rows.Count; i++)
                    {
                        strstatus = dts.Rows[i]["status"].ToString();
                    }

                    if (strstatus == "2")
                    {
                        //新增投资计划
                        await CProTZJHRule.UpdateTZJHBG(tzjhbg, GetUserId());
                    }
                    else
                    {
                        return Fail("数据状态为" + strstatus + ",未审核完成");
                    }

                }

                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }

        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> DelTZJHBG(string bgid)//
        {
            try
            {
                if (string.IsNullOrEmpty(bgid))
                {
                    return Fail("投资计划变更编号不能为空");
                }

                if (!await BaseEditPower.GetEditPower(bgid, BaseEditPower.TableName.投资计划变更))
                {
                    return Fail("响应失败:请确认数据权限");
                }


                //新增投资计划
                await CProTZJHRule.DeleteTZJHBG(bgid, GetUserId());

                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }


        #endregion



    }
}
